package posti.test.swf.web.action;

import java.util.Map;

import ognl.DefaultMemberAccess;
import ognl.Ognl;
import ognl.OgnlException;
import posti.test.domain.Book;
import posti.test.domain.Review;
import posti.test.swf.dao.Reference;
import posti.test.swf.dao.ReferenceImpl;
import posti.test.swf.web.dto.BookDTO;

public class BookDTOMapping implements Mapping/*<BookDTO, Book>*/  {
	public Object toDTO(Object domainObject) {
		try {
			Map ctx = Ognl.createDefaultContext(domainObject);
			Ognl.setMemberAccess(ctx, new DefaultMemberAccess(true));

			BookDTO bookDTO = new BookDTO();
			bookDTO.setId(((Book)domainObject).getId());
			bookDTO.setIsbn(((Book)domainObject).isbn());
			bookDTO.setTitle((String) Ognl.getValue("title", ctx, domainObject));
//			bookDTO.setReview(domainObject.getReview().getText());
			
			return bookDTO;
		} catch (OgnlException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}

	public boolean isNew(Object dto) {
		return ((BookDTO)dto).getId() == -1;
	}

	public Object newInstance(Object dto) {
		return new Book(((BookDTO)dto).getTitle());
	}

	public Reference reference(Object dto) {
		return new ReferenceImpl<Book>(Book.class, ((BookDTO)dto).getId());
	}

//	public void synchronize(Book book, BookDTO dto) {
	public void synchronize(Object domainObject, Object dtoObject) {
		try {
			Book book = (Book) domainObject;
			BookDTO dto = (BookDTO) dtoObject;
			book.setReview(new Review(dto.getReviewPoints()));
			book.getReview().setText(dto.getReview());
			Map ctx = Ognl.createDefaultContext(book);
			Ognl.setMemberAccess(ctx, new DefaultMemberAccess(true));

//			Ognl.setValue("id", ctx, book, dto.getId());
			Ognl.setValue("title", ctx, book, dto.getTitle());
		} catch (OgnlException e) {
			throw new RuntimeException(e);
		}
	}
}
